package com.okq.action;

import com.okq.action.base.BaseActionSupport;
import com.okq.entity.Menu;
import com.okq.entity.Role;
import com.okq.entity.RoleMenu;
import com.okq.entity.User;
import com.okq.service.*;
import com.okq.util.BaseTool;
import com.okq.util.PublicClass;
import com.okq.util.TimeTool;
import com.okq.util.page.Page;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.PrintWriter;
import java.util.*;
import java.util.Map.Entry;

/**
 * 描述 : 角色action
 * 作者 : zdl
 * 日期 : 2017/6/28 11:10
 */
public class RoleAction extends BaseActionSupport {

    private static final long serialVersionUID = -1943586884559531260L;
    /**
     * 角色接口
     */
    @Autowired
    private IRoleService roleServiceImpl;
    /**
     * 菜单接口
     */
    @Autowired
    private IMenuService menuServiceImpl;
    /**
     * 角色菜单接口
     */
    @Autowired
    private IRoleMenuService roleMenuServiceImpl;
    /**
     * 人员接口
     */
    @Autowired
    private IUserService userServiceImpl;
    /**
     * 系统日志接口
     */
    @Autowired
    private ILogService logServiceImpl;
    /**
     * 日志
     */
    private static final Logger logger = Logger.getLogger(RoleAction.class);

    /**
     * 分页开始条数
     */
    private int iDisplayStart;

    /**
     * 每页显示条数
     */
    private int iDisplayLength;

    private Role role;
    private String id;
    private String roleName;
    private String type;
    private String query;// 查询角色类型

    private String[] menuIds;// 菜单Ids

    /**
     * 获取列表
     *
     * @return json
     */
    public String getRoleList() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null) {
                if (iDisplayLength == 0) {
                    iDisplayLength = -1;
                }
                int pageNum = (int) (Math.ceil(iDisplayStart / iDisplayLength)) + 1;
                /* 分页信息 */
                Page<Role> pageInfo = new Page<>(iDisplayLength);
                pageInfo.setPageNo(pageNum);

                pageInfo = roleServiceImpl.pageByRole(pageInfo, role);
                int iTotalRecords = pageInfo.getTotalCount();
                int iTotalDisplayRecords = pageInfo.getTotalCount() < 0 ? 0 : pageInfo.getTotalCount();
                /* 得到结果 */
                List<Role> rList = pageInfo.getResult();
                /* 封装list */
                List<Map<String, Object>> roleMapList = new ArrayList<>();
                if (rList != null && !rList.isEmpty() && rList.size() > 0) {
                    int i = (pageNum - 1) * iDisplayLength + 1;
                    for (Role r : rList) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("no", i);// 序号
                        map.put("id", r.getId());
                        map.put("roleName", StringUtils.defaultString(r.getRoleName(), ""));
                        Integer roleType = r.getRoleType();
                        String roleTypeName = "";
                        if (roleType != null) {
                            switch (roleType) {
                                case 0:
                                    roleTypeName = "超级管理员";
                                    break;
                                case 1:
                                    roleTypeName = "管理员";
                                    break;
                                case 2:
                                    roleTypeName = "普通用户";
                                    break;
                                default:
                                    break;
                            }
                        }
                        map.put("roleTypeName", roleTypeName);
                        map.put("remark", StringUtils.defaultString(r.getRemark(), ""));
                        map.put("createUser", StringUtils.defaultString(r.getCreateUserName(), ""));
                        map.put("createTime", TimeTool.timestampToString(r.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
                        roleMapList.add(map);
                        i++;
                    }
                }
                Map<String, Object> jsonMap = new HashMap<>();
                jsonMap.put("iTotalRecords", iTotalRecords);
                jsonMap.put("iTotalDisplayRecords", iTotalDisplayRecords);
                jsonMap.put("aaData", roleMapList);

                String json = BaseTool.toJson(jsonMap);
                out.print(json);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 删除
     *
     * @return 是否成功标识
     */
    public String deleteRole() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && StringUtils.isNotBlank(id)) {
                List<User> uList = userServiceImpl.listUserByRoleId(id);
                if (uList != null && !uList.isEmpty() && uList.size() > 0) {
                    out.print(1);
                    return null;
                } else {
                    Role r = roleServiceImpl.getRoleById(id);
                    if (r != null) {
                        // 修改删除状态为1
                        r.setIsDelete(1);
                        r.setUpdateUserId(loginUser.getId());
                        r.setUpdateUserName(loginUser.getUserName());
                        roleServiceImpl.updateRole(r);
                        out.print(0);
                        //添加系统日志
                        String userName = loginUser.getUserName();
                        String nowTime = TimeTool.getNowTime();
                        String content = "用户：" + userName + "，于" + nowTime + " 删除角色：" + r.getRoleName() + "！";
                        PublicClass.addLog(userName, loginUser.getLoginName(), "角色管理", 2, content, logServiceImpl);
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 跳转到修改页面
     *
     * @return
     */
    @SuppressWarnings("all")
    public String toUpdatePage() {
        try {
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && StringUtils.isNotBlank(id)) {
                role = roleServiceImpl.getRoleById(id);
                if (role != null) {
                    return SUCCESS;
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
        return null;
    }

    /**
     * 保存
     *
     * @return 是否成功标识
     */
    public String saveRole() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && role != null) {
                if (StringUtils.isNotBlank(type) && type.equals("add")) {// 新增
                    Role r = roleServiceImpl.getRoleByName(role.getRoleName());
                    if (r != null) {
                        out.print("exist");
                        return null;
                    } else {
                        role.setId(BaseTool.getPK());
                        String userName = loginUser.getUserName();
                        if (StringUtils.isNotBlank(userName)) {
                            role.setCreateUserId(loginUser.getId());
                            role.setCreateUserName(userName);
                        }
                        roleServiceImpl.saveRole(role);
                        out.print("success");
                        //添加系统日志
                        String nowTime = TimeTool.getNowTime();
                        String content = "用户：" + userName + "，于" + nowTime + " 添加角色：" + role.getRoleName() + "！";
                        PublicClass.addLog(userName, loginUser.getLoginName(), "角色管理", 2, content, logServiceImpl);
                    }
                } else if (StringUtils.isNotBlank(type) && type.equals("update")) {// 修改
                    String newName = role.getRoleName();
                    Role ro = roleServiceImpl.getRoleById(role.getId());
                    if (ro != null) {
                        String oldName = ro.getRoleName();
                        if (StringUtils.isNotBlank(newName) && StringUtils.isNotBlank(oldName) && !newName.equals(oldName)) {
                            Role r = roleServiceImpl.getRoleByName(newName);
                            if (r != null) {
                                out.print("exist");
                                return null;
                            }
                        }
                        ro.setRoleName(newName);
                        ro.setRoleType(role.getRoleType());
                        ro.setRemark(role.getRemark());
                        String userName = loginUser.getUserName();
                        if (StringUtils.isNotBlank(userName)) {
                            ro.setUpdateUserId(loginUser.getId());
                            ro.setUpdateUserName(userName);
                        }
                        roleServiceImpl.updateRole(ro);
                        out.print("success");
                        //添加系统日志
                        String nowTime = TimeTool.getNowTime();
                        String content = "用户：" + userName + "，于" + nowTime + " 修改角色：" + newName + "！";
                        PublicClass.addLog(userName, loginUser.getLoginName(), "角色管理", 2, content, logServiceImpl);
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 跳转到角色授权页面
     *
     * @return SUCCESS
     */
    public String toRoleMenuConfig() {
        try {
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null) {
                Map<String, Menu> menuMap = menuServiceImpl.mapMenuByRoleId(id);
                Map<String, Menu> firstMenuMap = menuServiceImpl.mapMenuByLevel(menuMap, 1);
                Map<String, Menu> secondMenuMap = menuServiceImpl.mapMenuByLevel(menuMap, 2);
                Map<String, Menu> thirdMenuMap = menuServiceImpl.mapMenuByLevel(menuMap, 3);

                List<Menu> firstMenuList = new ArrayList<>();
                List<Menu> secondMenuList = new ArrayList<>();
                List<Menu> thirdMenuList = new ArrayList<>();

                for (Entry<String, Menu> entry : firstMenuMap.entrySet()) {
                    firstMenuList.add(entry.getValue());
                }
                for (Entry<String, Menu> entry : secondMenuMap.entrySet()) {
                    secondMenuList.add(entry.getValue());
                }
                for (Entry<String, Menu> entry : thirdMenuMap.entrySet()) {
                    thirdMenuList.add(entry.getValue());
                }

                Collections.sort(firstMenuList, new MenuComparator());
                Collections.sort(secondMenuList, new MenuComparator());
                Collections.sort(thirdMenuList, new MenuComparator());

                this.getRequest().setAttribute("firstMenuList", firstMenuList);
                this.getRequest().setAttribute("secondMenuList", secondMenuList);
                this.getRequest().setAttribute("thirdMenuList", thirdMenuList);

                Role r = roleServiceImpl.getRoleById(id);
                this.getRequest().setAttribute("role", r);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
        return SUCCESS;
    }

    /**
     * 角色授权
     *
     * @return 是否成功标识
     */
    public String addRoleMenu() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null) {
                if (StringUtils.isNotBlank(id)) {
                    // 先删除全部角色菜单
                    List<RoleMenu> rmList = roleMenuServiceImpl.listRoleMenuByRoleId(id);
                    if (rmList != null && !rmList.isEmpty() && rmList.size() > 0) {
                        for (RoleMenu rm : rmList) {
                            roleMenuServiceImpl.deleteRoleMenu(rm);
                        }
                    }
                    // 重新保存角色菜单
                    if (menuIds != null && menuIds.length > 0) {
                        for (String menuId : menuIds) {
                            RoleMenu roleMenu = new RoleMenu();
                            roleMenu.setId(BaseTool.getPK());
                            roleMenu.setRoleId(id);
                            roleMenu.setMenuId(menuId);
                            roleMenuServiceImpl.saveRoleMenu(roleMenu);
                        }
                    }
                    out.print(1);
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 获取角色信息
     *
     * @return json
     */
    public String findAllRole() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null) {
                List<Role> list = new ArrayList<>();
                List<Role> rList = roleServiceImpl.listAllRole();
                if (StringUtils.isNotBlank(query)) {
                    if (query.equals("all")) {
                        list = rList;
                    } else if (query.equals("opera")) {
                        String roleId = loginUser.getRoleId();
                        if (StringUtils.isNotBlank(roleId)) {
                            Role role = roleServiceImpl.getRoleById(roleId);
                            if (role != null) {
                                Integer roleType = role.getRoleType();
                                if (rList != null && !rList.isEmpty() && rList.size() > 0) {
                                    if (roleType == 0) {// 超级管理员
                                        for (Role r : rList) {
                                            if (r.getRoleType() != 0 && r.getRoleType() != null) {
                                                list.add(r);
                                            }
                                        }
                                    } else if (roleType == 1) {
                                        for (Role r : rList) {
                                            if (r.getRoleType() != 0 && r.getRoleType() != 1 && r.getRoleType() != null) {
                                                list.add(r);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                String data = BaseTool.toJson(list);
                out.print(data);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    public int getIDisplayStart() {
        return iDisplayStart;
    }

    public void setIDisplayStart(int iDisplayStart) {
        this.iDisplayStart = iDisplayStart;
    }

    public int getIDisplayLength() {
        return iDisplayLength;
    }

    public void setIDisplayLength(int iDisplayLength) {
        this.iDisplayLength = iDisplayLength;
    }

    public Role getRole() {
        return role;
    }

    public void setRole(Role role) {
        this.role = role;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getQuery() {
        return query;
    }

    public void setQuery(String query) {
        this.query = query;
    }

    public String[] getMenuIds() {
        return menuIds;
    }

    public void setMenuIds(String[] menuIds) {
        this.menuIds = menuIds;
    }

}

/**
 * 描述 : 菜单级别排序
 * 作者 : zdl
 * 日期 : 2017/3/15 11:56
 */
class MenuComparator implements Comparator<Menu> {
    @Override
    public int compare(Menu o1, Menu o2) {
        return o1.getOrderIndex() - o2.getOrderIndex();
    }
}
